package com.apexedu.biz.service.impl;

import com.apexedu.biz.Const;
import com.apexedu.biz.action.RegulationAction;
import com.apexedu.biz.entity.TRegulation;
import com.apexedu.biz.entity.TRegulationGx;
import com.apexedu.biz.entity.TRegulationLog;
import com.apexedu.biz.entity.client.CommandResult;
import com.apexedu.biz.entity.client.ResourceEntity;
import com.apexedu.biz.entity.client.RuleSummaryEntity;
import com.apexedu.framework.service.impl.AbstractBaseServiceSupport;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.action.IdLoginAction;
import com.apexedu.support.cache.CacheUtils;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.util.DateUtil;
import com.apexedu.util.FileUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.json.JsonUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@Service("regulationService")
public class RegulationServiceImpl extends AbstractBaseServiceSupport {
    private static final Log LOG = LogFactory.getLog(RegulationAction.class);
    private static StringBuilder zNodes = new StringBuilder();

    @Resource(name = "authServiceImpl")
    AuthServiceImpl authService;

    @SuppressWarnings("unchecked")
    @Override
    public List<?> list(Object myaction, Pager pager) throws Exception {
        List<Object> params = new LinkedList<Object>();
        String sql = "  from T_REGULATION t where 1=1 ";
        long c = DBUtil.count("select count(*) as c " + sql, params.toArray());
        pager.setTotalRows(c);
        sql += " order by jlcssj desc";
        String hql_column = "select wid,bt,nrzy,fjdz,fjmc,dyzdscfjdz,dyzdscfjmc,djs,jlcssj,jlxgsj,ysxqfjurl,gzzdfjurl,ysxqfjsm,gzzdfjsm,(select count(*) from T_REGULATION_GX where gzwid=t.wid) as zys,cjr";
        List<TRegulation> list = DBUtil.queryPageBeanList(pager, hql_column + sql, TRegulation.class, params.toArray());
        return list;
    }

    @Override
    public void load(Object myaction) throws Exception {
        RegulationAction action = (RegulationAction) myaction;
        String wid = action.getWid();
        TRegulation accessAppReg = getBaseDao().findById(TRegulation.class, wid);
        action.setRegulation(accessAppReg);
    }

    @Override
    public boolean remove(Object myaction) throws Exception {
        RegulationAction action = (RegulationAction) myaction;
        String ids = action.getWid();
        boolean deleteSuccess = getBaseDao().deleteAll("TRegulation", "wid", "=", ids);
        BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_T_REGULATION, Const.LOG_ACTION_DEL,
                IdLoginAction.getIpAddr(action.getRequest()), "删除业务规则");
        return deleteSuccess;
    }

    @Override
    public void saveOrUpdate(Object myaction) throws Exception {
        RegulationAction action = (RegulationAction) myaction;
        TRegulation regulation = action.getRegulation();
        Map<String, String> uploadResult = fileUpload(action);      //附件上传

        if (regulation != null) {
            if (StringUtil.isNotBlank(regulation.getWid())) {
                //保存摘要
                regulation.setNrzy(summary(regulation.getNr(), 100));
                //创建人
                regulation.setCjr(action.getUserloginid());
                //修改时间
                regulation.setJlxgsj(new Date());
                if (StringUtil.isNotBlank(uploadResult.get("fjdz"))) {
                    //附件地址
                    regulation.setFjdz(uploadResult.get("fjdz"));
                    //原名
                    regulation.setFjmc(uploadResult.get("filename"));
                }


                if (StringUtil.isNotBlank(uploadResult.get("dyzdscFileSaveName"))) {
                    //对应制度上传
                    regulation.setDyzdscfjdz(uploadResult.get("dyzdscFileSaveName"));
                    //原名
                    regulation.setDyzdscfjmc(uploadResult.get("dyzdscFileName"));
                }

                if (StringUtil.isNotBlank(uploadResult.get("ysxqfjFileSaveName"))) {
                    //原始需求附件
                    regulation.setYsxqfjurl(uploadResult.get("ysxqfjFileSaveName"));
                    //原名
                    regulation.setYsxqfjmc(uploadResult.get("ysxqfjFileName"));
                }

                if (StringUtil.isNotBlank(uploadResult.get("gzzdfjFileSaveName"))) {
                    //原始需求附件
                    regulation.setGzzdfjurl(uploadResult.get("gzzdfjFileSaveName"));
                    //原名
                    regulation.setGzzdfjmc(uploadResult.get("gzzdfjFileName"));
                }

                /**记录规则变化**/
                saveRegulationLogs(regulation, action.getLoginuser().getUserid());
                baseDao.updateNotNull(regulation);
                BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_T_REGULATION, Const.LOG_ACTION_UPDATE,
                        IdLoginAction.getIpAddr(action.getRequest()),"业务规则修改");
            } else {
                regulation.setWid(SeqFactory.getNewSequenceAlone());
                //创建人
                regulation.setCjr(action.getUserloginid());
                //创建时间
                regulation.setJlcssj(new Date());
                //保存摘要
                regulation.setNrzy(summary(regulation.getNr(), 100));
                regulation.setDjs(0);
                regulation.setZys(0);
                //附件地址
                regulation.setFjdz(uploadResult.get("fjdz"));
                //原名
                regulation.setFjmc(uploadResult.get("filename"));

                //对应制度上传
                regulation.setDyzdscfjdz(uploadResult.get("dyzdscFileSaveName"));
                //原名
                regulation.setDyzdscfjmc(uploadResult.get("dyzdscFileName"));

                //原始需求附件
                regulation.setYsxqfjurl(uploadResult.get("ysxqfjFileSaveName"));
                //原名
                regulation.setYsxqfjmc(uploadResult.get("ysxqfjFileName"));

                //规章制度附件
                regulation.setGzzdfjurl(uploadResult.get("gzzdfjFileSaveName"));
                //原名
                regulation.setGzzdfjmc(uploadResult.get("gzzdfjFileName"));
                baseDao.save(regulation);
                BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_T_REGULATION, Const.LOG_ACTION_SAVE,
                        IdLoginAction.getIpAddr(action.getRequest()),"新增业务规则");
            }
        }
    }

    /**
     * 获取描述的摘要内容  不包含 html标签
     *
     * @param source 内容
     * @param length 长度
     * @return
     */
    public String summary(String source, int length) {
        if (StringUtil.isEmpty(source)) return "";
        String str = HtmlUtils.htmlUnescape(source).replaceAll("&[^;]+;", "").replaceAll("<[.[^<]]*>", "").replaceAll("\r|\n", "");      //去掉html标签
        if (StringUtil.isNotEmpty(str) && str.length() > length) {
            str = str.substring(0, length);
            str = str + "...";
        }
        return str;
    }

    /**
     * 保存规则关系
     *
     * @param action
     * @return
     */
    public String szgxSave(RegulationAction action) throws Exception {
        String zywid = action.getZywid();
        if (StringUtil.isEmpty(zywid)) return "资源编号不能为空！";
        //保存之前先删除之前的关系
        int deleteCount = DBUtil.executeSQL("delete from T_REGULATION_GX where zywid=?", zywid);
        BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_T_REGULATION_GX,Const.LOG_ACTION_DEL,
                IdLoginAction.getIpAddr(action.getRequest()),"删除之前的规则关系");
        LOG.info("用户【" + action.getUserloginid() + "】删除资源与规则关系 " + deleteCount + " 条！");
        String selectedGZ = action.getSelectedGZ();
        if (StringUtil.isNotBlank(selectedGZ)) {
            String[] array = selectedGZ.split("\\|");
            if (array != null && array.length > 0) {
                for (int i = 0; i < array.length; i++) {
                    String gzwid = array[i];
                    TRegulationGx gx = new TRegulationGx();
                    gx.setWid(SeqFactory.getNewSequenceAlone());
                    gx.setZywid(zywid);
                    gx.setGzwid(gzwid);
                    baseDao.save(gx);
                }
                BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_T_REGULATION_GX,Const.LOG_ACTION_SAVE,
                        IdLoginAction.getIpAddr(action.getRequest()),"保存规则关系");
            }
        } else {
            return "保存失败，请至少选择一个规则！";
        }
        return "ok";
    }

    /**
     * 保存规则设置资源关系
     *
     * @param action
     * @return
     */
    public String szzySave(RegulationAction action) throws Exception {
        String gzwid = action.getGzwid();
        if (StringUtil.isEmpty(gzwid)) return "规则编号不能为空！";
        //保存之前先删除之前的关系
        int deleteCount = DBUtil.executeSQL("delete from T_REGULATION_GX where gzwid=?", gzwid);
        BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_T_REGULATION_GX,Const.LOG_ACTION_DEL,
                IdLoginAction.getIpAddr(action.getRequest()),"删除之前的规则关系");
        LOG.info("用户【" + action.getUserloginid() + "】删除资源与规则关系 " + deleteCount + " 条！");
        String selectedZY = action.getSelectedZY();
        if (StringUtil.isNotBlank(selectedZY)) {
            String[] array = selectedZY.split("\\|");
            if (array != null && array.length > 0) {
                for (int i = 0; i < array.length; i++) {
                    String zywid = array[i];
                    TRegulationGx gx = new TRegulationGx();
                    gx.setWid(SeqFactory.getNewSequenceAlone());
                    gx.setZywid(zywid);
                    gx.setGzwid(gzwid);
                    baseDao.save(gx);
                }
            }
        } else {
            return "保存失败，请至少选择一个资源！";
        }
        return "ok";
    }


    /**
     * 加载
     *
     * @param zywid 资源wid
     * @return
     */
    public String szgxLoad(String zywid) {
        if (StringUtil.isEmpty(zywid)) return "";
        String sql = "select gzwid from T_REGULATION_GX where zywid=?";

        List<Map<String, String>> list = DBUtil.queryForList(sql, zywid);
        if (list != null && list.size() > 0) {
            StringBuffer resultStr = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                resultStr.append(list.get(i).get("gzwid"));
                resultStr.append("|");
            }
            return resultStr.toString();
        }
        return null;
    }

    /**
     * 设置资源加载
     *
     * @return
     */
    public void szzyLoad(RegulationAction action) throws Exception {
        String gzwid = action.getGzwid();
        if (StringUtil.isEmpty(gzwid)) {
            throw new Exception("规则编号为空！");
        }
        String sql = "select m.menuid,m.menuname from T_REGULATION_GX t left join T_Sys_Menu m on t.zywid=m.menuid  where t.gzwid=?";
        StringBuilder resultStr = new StringBuilder();
        List<Map<String, String>> list = DBUtil.queryForList(sql, gzwid);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                resultStr.append(list.get(i).get("menuid")).append("|");
            }
        }
        action.setSelectedZY(resultStr.toString());
        action.setZyTreeJsonData(getZYTreeJsonData(true));
    }

    /**
     * 已经选择的数据json信息，主要为了中文名称显示
     *
     * @param action
     */
    public void szgxJsonData(RegulationAction action) {
        String selectedGZ = action.getSelectedGZ();
        action.setJsonDate("{}");
        if (StringUtil.isNotBlank(selectedGZ)) {
            String[] array = selectedGZ.split("\\|");

            if (array != null && array.length > 0) {
                StringBuilder sqlwhere = new StringBuilder(" in (");
                for (int i = 0; i < array.length; i++) {
                    String gzwid = array[i];
                    if (StringUtil.isNotBlank(gzwid)) {
                        sqlwhere.append("'").append(gzwid).append("'");
                        if (i < array.length - 1) {
                            sqlwhere.append(",");
                        }
                    }

                }
                sqlwhere.append(")");

                String sql = "select wid,bt from T_REGULATION where wid " + sqlwhere;
                List<Map<String, String>> list = DBUtil.queryForList(sql);
                Map<String, String> map = new HashMap<String, String>();
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        map.put(list.get(i).get("wid"), list.get(i).get("bt"));
                    }
                }
                String jsonstr = JsonUtil.getJSONString(map);
                if (StringUtil.isNotBlank(jsonstr)) {
                    action.setJsonDate(jsonstr);
                }
            }
        }
    }

    /**
     * 获取资源树（缓存）
     *
     * @param flag 业务系统资源目录是否展开
     * @return
     */
    public String getZYTreeJsonData(boolean flag) {
        //CacheUtils.delete("ZYTreeJsonData");
        if (null != CacheUtils.get("ZYTreeJsonData")) {
            return (String) CacheUtils.get("ZYTreeJsonData");
        } else {
            zNodes.setLength(0);  //清空
            zNodes.append("[");
            zNodes.append("{ id:'000', pId:'0', name:\"资源管理中心\", open:true},");
            String sql = "select appid as id,appname as text from t_access_app_reg a  order by ordernum desc, id";
            List<Map<String, String>> list = DBUtil.queryForList(sql);
            if (null != list && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Map<String, String> tempMap = list.get(i);
                    zNodes.append("{ id:").append("'").append(tempMap.get("id")).append("'").append(", pId:").append("'").append("000").append("'").append(", name:\"").append(tempMap.get("text")).append("\", open:true},");
                    //加入子节点
                    String childSql = "select menuid as id, menuname  as text from T_Sys_Menu where belongtoapp=? and length(menuid) = 6 and length(?) > 18 order by ordernum desc";
                    List<Map<String, String>> childList = DBUtil.queryForList(childSql, tempMap.get("id"), tempMap.get("id"));
                    if (childList != null && childList.size() > 0) {
                        for (int childI = 0; childI < childList.size(); childI++) {
                            Map<String, String> childTempMap = childList.get(childI);
                            zNodes.append("{ id:").append("'").append(childTempMap.get("id")).append("'").append(", pId:").append("'").append(tempMap.get("id")).append("'").append(", name:\"").append(childTempMap.get("text")).append("\", open:" + flag + "},");
                            //下面还存在子节点，使用递归的方式获取到
                            getChildNodes(childTempMap.get("id"));
                        }
                    }
                }
            }
            //去掉最后一位,
            String jsonStr = zNodes.substring(0, zNodes.length() - 1) + "]";
            CacheUtils.put("ZYTreeJsonData", jsonStr);
            if (StringUtil.isNotEmpty(jsonStr)) {
                return jsonStr;
            } else {
                return "[]";
            }
        }
    }

    public static void getChildNodes(String parentid) {
        String sql = "select menuid as id, menuname  as text from T_Sys_Menu where upmenuid=? order by ordernum desc";
        List<Map<String, String>> list = DBUtil.queryForList(sql, parentid);
        if (list == null || list.size() <= 0)
            return;
        for (int i = 0; i < list.size(); i++) {
            String sqlCount = "select count(*) from T_Sys_Menu where upmenuid=?";
            Map<String, String> tempMap = list.get(i);
            String myid = tempMap.get("id");
            zNodes.append("{ id:").append("'").append(myid).append("'").append(", pId:").append("'").append(parentid).append("'").append(", name:\"").append(tempMap.get("text")).append("\", open:true},");
            int c = DBUtil.count(sqlCount, myid);
            if (c > 0) {
                getChildNodes(myid);
            }
        }
    }

    /**
     * 附件上传  代码太过冗余而且容易出错，时间宽裕时整一下
     *
     * @param action
     */
    private Map<String, String> fileUpload(RegulationAction action) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String relativePath = "upload" + File.separator + DateUtil.formatDate(new Date(), "yyyyMM");        //相对路径
        String savePath = FileUtil.getFileStoreRootPath() + relativePath;
        File fj = action.getFj();   //上传的文件
        String filename = action.getFjFileName();      //文件原名
        String fileSaveName = null;     //文件保存名


        File dyzdsc = action.getDyzdsc();       //对应制度上传
        String dyzdscFileName = action.getDyzdscFileName();  //对应制度文件名
        String dyzdscFileSaveName = null;     //文件保存名

        File ysxqfj = action.getYsxqfj();                                   //原始需求附件
        String ysxqfjFileName = action.getYsxqfjFileName(); //原始需求附件文件名
        String ysxqfjFileSaveName = null;

        File gzzdfj = action.getGzzdfj();               //规章制度附件
        String gzzdfjFileName = action.getGzzdfjFileName();        //规章制度附件文件名
        String gzzdfjFileSaveName = null;                        //保存的路径


        //设置允许上传的文件类型
        List<String> allowExtList = new ArrayList<String>();
        allowExtList.add("doc");
        allowExtList.add("docx");
        allowExtList.add("txt");
        allowExtList.add("xls");
        allowExtList.add("xlsx");

        if (fj != null && filename != null) {
            String fileExtName = FileUtil.getFileExt(filename); //扩展名
            if (!allowExtList.contains(fileExtName.toLowerCase())) {
                action.addActionError("保存失败！只允许上传" + allowExtList + "类型的文件");
                throw new RuntimeException("只允许上传 " + allowExtList + "类型的文件！");
            }
            //保存文件的名称
            fileSaveName = SeqFactory.getNewSequenceAlone() + "." + fileExtName;
            File savefile = new File(new File(savePath), fileSaveName);
            if (!savefile.getParentFile().exists())
                try {
                    savefile.getParentFile().mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            FileUtils.copyFile(fj, savefile);
        } else {
            //新增没有上传文件给出提示
            filename = "";
            fileSaveName = "";
        }

        if (dyzdsc != null && dyzdscFileName != null) {
            String fileExtName = FileUtil.getFileExt(dyzdscFileName); //扩展名
            if (!allowExtList.contains(fileExtName.toLowerCase())) {
                action.addActionError("保存失败！只允许上传" + allowExtList + "类型的文件");
                throw new RuntimeException("只允许上传 " + allowExtList + "类型的文件！");
            }
            //保存文件的名称
            dyzdscFileSaveName = SeqFactory.getNewSequenceAlone() + "." + fileExtName;
            File savefile = new File(new File(savePath), dyzdscFileSaveName);
            if (!savefile.getParentFile().exists())
                try {
                    savefile.getParentFile().mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            FileUtils.copyFile(dyzdsc, savefile);
        } else {
            //新增没有上传文件给出提示
            dyzdscFileName = "";
            dyzdscFileSaveName = "";
        }

        if (ysxqfj != null && ysxqfjFileName != null) {
            String fileExtName = FileUtil.getFileExt(ysxqfjFileName); //扩展名
            if (!allowExtList.contains(fileExtName.toLowerCase())) {
                action.addActionError("保存失败！只允许上传" + allowExtList + "类型的文件");
                throw new RuntimeException("只允许上传 " + allowExtList + "类型的文件！");
            }
            //保存文件的名称
            ysxqfjFileSaveName = SeqFactory.getNewSequenceAlone() + "." + fileExtName;
            File savefile = new File(new File(savePath), ysxqfjFileSaveName);
            if (!savefile.getParentFile().exists()) {
                try {
                    savefile.getParentFile().mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            FileUtils.copyFile(ysxqfj, savefile);
        } else {
            //新增没有上传文件给出提示
            ysxqfjFileName = "";
            ysxqfjFileSaveName = "";
        }

        if (gzzdfj != null && gzzdfjFileName != null) {
            String fileExtName = FileUtil.getFileExt(gzzdfjFileName); //扩展名
            if (!allowExtList.contains(fileExtName.toLowerCase())) {
                action.addActionError("保存失败！只允许上传" + allowExtList + "类型的文件");
                throw new RuntimeException("只允许上传 " + allowExtList + "类型的文件！");
            }
            //保存文件的名称
            gzzdfjFileSaveName = SeqFactory.getNewSequenceAlone() + "." + fileExtName;
            File savefile = new File(new File(savePath), gzzdfjFileSaveName);
            if (!savefile.getParentFile().exists()) {
                try {
                    savefile.getParentFile().mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            FileUtils.copyFile(gzzdfj, savefile);
        } else {
            //新增没有上传文件给出提示
            gzzdfjFileName = "";
            gzzdfjFileSaveName = "";
        }


        map.put("filename", filename);

        if (StringUtil.isNotEmpty(fileSaveName)) {
            String fjdz_map = relativePath + File.separator + fileSaveName;
            map.put("fjdz", fjdz_map.replaceAll("\\\\|/", "/"));   //文件相对路径
        } else {
            map.put("fjdz", "");   //报表文件的文件相对路径
        }

        map.put("dyzdscFileName", dyzdscFileName);
        if (StringUtil.isNotEmpty(dyzdscFileName)) {
            String dyzdscFileSaveName_map = relativePath + File.separator + dyzdscFileSaveName;
            map.put("dyzdscFileSaveName", dyzdscFileSaveName_map.replaceAll("\\\\|/", "/"));   //文件相对路径
        } else {
            map.put("dyzdscFileSaveName", "");   //报表文件的文件相对路径
        }


        map.put("ysxqfjFileName", ysxqfjFileName);
        if (StringUtil.isNotEmpty(ysxqfjFileName)) {
            String dyzdscFileSaveName_map = relativePath + File.separator + ysxqfjFileSaveName;
            map.put("ysxqfjFileSaveName", dyzdscFileSaveName_map.replaceAll("\\\\|/", "/"));   //文件相对路径
        } else {
            map.put("ysxqfjFileSaveName", "");   //文件相对路径
        }

        map.put("gzzdfjFileName", gzzdfjFileName);
        if (StringUtil.isNotEmpty(gzzdfjFileName)) {
            String dyzdscFileSaveName_map = relativePath + File.separator + gzzdfjFileSaveName;
            map.put("gzzdfjFileSaveName", dyzdscFileSaveName_map.replaceAll("\\\\|/", "/"));   //文件相对路径
        } else {
            map.put("gzzdfjFileSaveName", "");   //文件相对路径
        }


        return map;
    }

    /**
     * 查询指定资源的规则说明
     *
     * @param srcId 客户端的资源编号（对应bizcode）
     * @return
     */
    public CommandResult getRules(String basePath, String clientAppId, String srcId) {
        clientAppId = authService.checkClientAppId(clientAppId); // 断言接入号正确

        ResourceEntity resourceEntity = new ResourceEntity();
        resourceEntity.setSrcId(srcId);
        resourceEntity.setAppId(clientAppId);
        List<TRegulation> regulationList = baseDao.findByHqlWithSecondCache(true, "select b from TRegulationGx a, TRegulation b, TSysMenu c where a.gzwid=b.wid and a.zywid=c.menuid and c.belongtoapp=? and c.bizcode=?", clientAppId, srcId);       //关系列表
        if (regulationList != null && regulationList.size() > 0) {
            for (int i = 0; i < regulationList.size(); i++) {
                TRegulation regulation = regulationList.get(i);
                RuleSummaryEntity ruleDocEntity = new RuleSummaryEntity();
                ruleDocEntity.setRuleId(regulation.getWid());
                ruleDocEntity.setRuleUrl(basePath + "/s/rulesdetail/" + regulation.getWid());
                ruleDocEntity.setRuleContent(regulation.getNr());
                ruleDocEntity.setRuleName(regulation.getBt());

                if (StringUtil.isNotEmpty(regulation.getFjdz()))
                    ruleDocEntity.setXqgzUrl(basePath + "/" + regulation.getFjdz());     //需求规则
                if (StringUtil.isNotEmpty(regulation.getDyzdscfjdz()))
                    ruleDocEntity.setDyzdUrl(basePath + "/" + regulation.getDyzdscfjdz());       //对应制度

                /**以下2014.02.26新增**/
                ruleDocEntity.setYsxqfjUrl(regulation.getYsxqfjurl());               //原始需求附件下载地址
                ruleDocEntity.setGzzdfjUrl(regulation.getGzzdfjurl());               //规章制度附件下载地址
                ruleDocEntity.setYsxqfjsm(regulation.getYsxqfjsm());                //原始需求附件说明
                ruleDocEntity.setGzzdfjsm(regulation.getGzzdfjsm());              //规章制度附件说明
                ruleDocEntity.setSjgw(regulation.getSjgw());                           //涉及岗位
                ruleDocEntity.setGzms(regulation.getGzms());                        //规则描述
                ruleDocEntity.setGzbgjl(getRegulationLogs(regulation.getWid()));                                              //规则变更记录
                ruleDocEntity.setGzpzUrl(regulation.getGzpzurl());                  //规则配置


                resourceEntity.getRuleEntities().add(ruleDocEntity);
            }
        }

        CommandResult result = new CommandResult();
        result.setResourceEntity(resourceEntity);
        return result;
    }

    /**
     * 前台规则详情页面
     */
    public void rulesDetail(String gzwid, ModelMap model) throws Exception {

        if (StringUtils.isEmpty(gzwid)) {
            throw new Exception("规则编号为空！");
        }
        TRegulation regulation = baseDao.findById(TRegulation.class, gzwid);
        if (regulation == null) {
            throw new Exception("访问的页面不存在！");
        } else {
            model.put("regulation", regulation);
            //点击率+1
            regulation.setDjs(regulation.getDjs() + 1);
            baseDao.update(regulation);
        }
    }

    /**
     * 保存规则变化记录
     *
     * @param regulation 用户编辑产生的规则实体
     * @param userid     操作用户
     */
    public void saveRegulationLogs(TRegulation regulation, String userid) {
        if (regulation != null) {
            if (StringUtil.isNotEmpty(regulation.getWid())) {
                // TRegulation db = baseDao.findById(TRegulation.class,regulation.getWid());       //数据库中存的规则信息
                TRegulationLog log = new TRegulationLog();
                log.setWid(SeqFactory.getNewSequenceAlone());
                log.setSj(new Date());
                log.setUserid(userid);
                log.setGzid(regulation.getWid());
                /**比较新的与数据库中保存的不同**/
                //TODO:保存描述信息
                baseDao.save(log);
                BusinessLogUtil.log(userid, Const.CZDX_T_REGULATION_LOG,Const.LOG_ACTION_SAVE,"","保存规则变化记录");
            }
        }
    }

    /**
     * 获取规则变更日志
     *
     * @param regulationID 规则 ID
     * @return
     */
    public String getRegulationLogs(String regulationID) {
        String sql = "select u.username,to_char(sj,'yyyy-mm-dd hh:mi:ss') as sj,ms from T_REGULATION_LOG l left join T_SYS_USER u on l.userid = u.userid where l.gzid=? order by l.sj desc";
        List<Map<String, String>> list = DBUtil.queryForList(sql, regulationID);
        StringBuffer sb = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, String> map = list.get(i);
                String username = map.get("username");
                String sj = map.get("sj");
                String ms = map.get("ms");
                sb.append("【").append(sj).append("】").append(username);
                if (StringUtil.isNotEmpty(ms)) {
                    sb.append("=>").append(ms);
                } else {
                    sb.append("进行了修改");
                }
                sb.append("\n");
            }
        } else {
            return "暂无";
        }
        return sb.toString();
    }

}
